using Microsoft.AspNetCore.Mvc;
using AuthService.Application.Services;
using Microsoft.AspNetCore.Authorization;

namespace AuthService.Api.Controllers;

/// <summary>
/// 动态API管理控制器
/// 用于管理动态API端点的创建、更新、删除等操作
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize] // 需要认证才能访问
public class DynamicApiManagementController : ControllerBase
{
    private readonly IDynamicApiMappingService _mappingService;
    private readonly IDynamicApiService _dynamicApiService;
    private readonly ILogger<DynamicApiManagementController> _logger;

    public DynamicApiManagementController(
        IDynamicApiMappingService mappingService,
        IDynamicApiService dynamicApiService,
        ILogger<DynamicApiManagementController> logger)
    {
        _mappingService = mappingService;
        _dynamicApiService = dynamicApiService;
        _logger = logger;
    }

    /// <summary>
    /// 获取所有动态API端点
    /// </summary>
    /// <returns>动态API端点列表</returns>
    [HttpGet("endpoints")]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> GetAllEndpoints()
    {
        try
        {
            _logger.LogInformation("获取所有动态API端点");

            var endpoints = await _mappingService.GetAllEndpointsAsync();

            var result = endpoints.Select(e => new
            {
                e.Id,
                e.Name,
                e.Description,
                Method = e.Method.ToString(),
                e.PathTemplate,
                e.TargetService,
                e.IsEnabled,
                e.RequireAuthentication,
                e.RequiredRoles,
                e.Version,
                e.Tags,
                e.Priority,
                e.CreatedAt,
                e.UpdatedAt,
                e.LastAccessedAt,
                e.AccessCount
            });

            return Ok(new { Data = result, Total = result.Count() });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取动态API端点失败");
            return StatusCode(500, new { Message = "获取动态API端点失败", Error = ex.Message });
        }
    }

    /// <summary>
    /// 刷新动态API映射
    /// 重新扫描服务层方法并更新API端点配置
    /// </summary>
    /// <returns>刷新结果</returns>
    [HttpPost("refresh")]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> RefreshMappings()
    {
        try
        {
            _logger.LogInformation("开始刷新动态API映射");

            var createdCount = await _mappingService.RefreshMappingsAsync();

            return Ok(new
            {
                Message = "动态API映射刷新成功",
                CreatedCount = createdCount,
                RefreshedAt = DateTime.UtcNow
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "刷新动态API映射失败");
            return StatusCode(500, new { Message = "刷新动态API映射失败", Error = ex.Message });
        }
    }

    /// <summary>
    /// 启用或禁用API端点
    /// </summary>
    /// <param name="id">端点ID</param>
    /// <param name="request">启用/禁用请求</param>
    /// <returns>操作结果</returns>
    [HttpPut("endpoints/{id:guid}/toggle")]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(404)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> ToggleEndpoint(Guid id, [FromBody] ToggleEndpointRequest request)
    {
        try
        {
            _logger.LogInformation("切换端点状态: {EndpointId}, 启用: {IsEnabled}", id, request.IsEnabled);

            var success = await _mappingService.ToggleEndpointAsync(id, request.IsEnabled);

            if (!success)
            {
                return NotFound(new { Message = "端点不存在" });
            }

            return Ok(new
            {
                Message = $"端点已{(request.IsEnabled ? "启用" : "禁用")}",
                EndpointId = id,
                IsEnabled = request.IsEnabled,
                UpdatedAt = DateTime.UtcNow
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "切换端点状态失败: {EndpointId}", id);
            return StatusCode(500, new { Message = "切换端点状态失败", Error = ex.Message });
        }
    }

    /// <summary>
    /// 临时方法：禁用所有动态API端点的认证要求
    /// </summary>
    /// <returns>更新结果</returns>
    [HttpPost("disable-auth")]
    [AllowAnonymous]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> DisableAuthenticationForAllEndpoints()
    {
        try
        {
            _logger.LogInformation("开始禁用所有动态API端点的认证要求");

            // 获取所有动态API端点
            var endpoints = await _mappingService.GetAllEndpointsAsync();
            var dynamicEndpoints = endpoints.Where(e => e.PathTemplate.StartsWith("/api/dynamic/")).ToList();

            int updatedCount = 0;
            foreach (var endpoint in dynamicEndpoints)
            {
                if (endpoint.RequireAuthentication)
                {
                    endpoint.RequireAuthentication = false;
                    await _dynamicApiService.UpdateEndpointAsync(endpoint);
                    updatedCount++;
                    _logger.LogInformation("已禁用端点认证: {EndpointName} - {PathTemplate}",
                        endpoint.Name, endpoint.PathTemplate);
                }
            }

            return Ok(new
            {
                Message = $"成功禁用了 {updatedCount} 个端点的认证要求",
                UpdatedCount = updatedCount,
                TotalEndpoints = dynamicEndpoints.Count,
                UpdatedAt = DateTime.UtcNow
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "禁用端点认证失败");
            return StatusCode(500, new { Message = "禁用端点认证失败", Error = ex.Message });
        }
    }

    /// <summary>
    /// 为指定服务创建动态API端点
    /// </summary>
    /// <param name="request">创建请求</param>
    /// <returns>创建结果</returns>
    [HttpPost("services/map")]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(400)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> MapServiceEndpoints([FromBody] MapServiceRequest request)
    {
        try
        {
            _logger.LogInformation("为服务创建动态API端点: {ServiceName}, 前缀: {Prefix}",
                request.ServiceName, request.PathPrefix);

            if (string.IsNullOrWhiteSpace(request.ServiceName))
            {
                return BadRequest(new { Message = "服务名称不能为空" });
            }

            if (string.IsNullOrWhiteSpace(request.PathPrefix))
            {
                return BadRequest(new { Message = "路径前缀不能为空" });
            }

            // 这里需要根据服务名称动态创建端点
            // 由于泛型限制，这里简化处理
            var message = $"服务 {request.ServiceName} 的端点映射请求已接收，路径前缀: {request.PathPrefix}";

            return Ok(new
            {
                Message = message,
                ServiceName = request.ServiceName,
                PathPrefix = request.PathPrefix,
                RequestedAt = DateTime.UtcNow
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "为服务创建端点失败: {ServiceName}", request.ServiceName);
            return StatusCode(500, new { Message = "为服务创建端点失败", Error = ex.Message });
        }
    }

    /// <summary>
    /// 获取动态API统计信息
    /// </summary>
    /// <returns>统计信息</returns>
    [HttpGet("statistics")]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> GetStatistics()
    {
        try
        {
            _logger.LogInformation("获取动态API统计信息");

            var endpoints = await _mappingService.GetAllEndpointsAsync();
            var endpointList = endpoints.ToList();

            var statistics = new
            {
                TotalEndpoints = endpointList.Count,
                EnabledEndpoints = endpointList.Count(e => e.IsEnabled),
                DisabledEndpoints = endpointList.Count(e => !e.IsEnabled),
                AutoGeneratedEndpoints = endpointList.Count(e => e.Tags.Contains("auto-generated")),
                ManualEndpoints = endpointList.Count(e => !e.Tags.Contains("auto-generated")),
                TotalAccess = endpointList.Sum(e => e.AccessCount),
                MostAccessedEndpoint = endpointList
                    .OrderByDescending(e => e.AccessCount)
                    .Select(e => new { e.Name, e.AccessCount })
                    .FirstOrDefault(),
                RecentlyCreated = endpointList
                    .Where(e => e.CreatedAt > DateTime.UtcNow.AddDays(-7))
                    .Count(),
                ByHttpMethod = endpointList
                    .GroupBy(e => e.Method.ToString())
                    .ToDictionary(g => g.Key, g => g.Count()),
                ByTargetService = endpointList
                    .Where(e => !string.IsNullOrEmpty(e.TargetService))
                    .GroupBy(e => e.TargetService)
                    .ToDictionary(g => g.Key!, g => g.Count())
            };

            return Ok(statistics);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取动态API统计信息失败");
            return StatusCode(500, new { Message = "获取动态API统计信息失败", Error = ex.Message });
        }
    }
}

/// <summary>
/// 切换端点状态请求
/// </summary>
public class ToggleEndpointRequest
{
    /// <summary>
    /// 是否启用
    /// </summary>
    public bool IsEnabled { get; set; }
}

/// <summary>
/// 映射服务请求
/// </summary>
public class MapServiceRequest
{
    /// <summary>
    /// 服务名称
    /// </summary>
    public string ServiceName { get; set; } = string.Empty;

    /// <summary>
    /// 路径前缀
    /// </summary>
    public string PathPrefix { get; set; } = string.Empty;
}
